package com.timemanager.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.timemanager.R;
import com.timemanager.application.MyApplication;
import com.timemanager.db.TimeManagerDB;
import com.timemanager.model.EventTime;
import com.timemanager.model.Time;
import com.timemanager.util.Utility;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AddEventTimeActivity extends AppCompatActivity implements View.OnClickListener{

    private TextView titleText;

    private TextView eventName;

    private TextView startDate;

    private TextView startTime;

    private Button btnReset;

    private EditText hour;

    private EditText min;

    private Button btnSetStartDate;

    private Button btnSetStartTime;

    private Button btnSave;

    int getHour;

    int getMin;

    private TimeManagerDB timeManagerDB;

    private int year, monthOfYear, dayOfMonth, hourOfDay, minute;

    private StringBuilder startDateTime = new StringBuilder();

    private Time time = new Time();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_event_time);
        titleText = (TextView)findViewById(R.id.title_text);
        eventName = (TextView)findViewById(R.id.event_name);
        startTime = (TextView) findViewById(R.id.start_time);
        startDate = (TextView) findViewById(R.id.start_date);
        btnReset = (Button)findViewById(R.id.btn_reset);
        hour = (EditText)findViewById(R.id.hour);
        min = (EditText)findViewById(R.id.min);
        btnSetStartTime = (Button)findViewById(R.id.btn_set_start_time);
        btnSetStartDate = (Button)findViewById(R.id.btn_set_start_date);
        btnSave = (Button)findViewById(R.id.btn_save);
        btnReset.setOnClickListener(this);
        btnSetStartTime.setOnClickListener(this);
        btnSetStartDate.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        timeManagerDB = TimeManagerDB.getInstance(this);
        titleText.setText("编辑将要添加的活动：");
        eventName.setText("添加活动：" + getIntent().getStringExtra("event_name"));
        //获取Calendar实例
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        minute = calendar.get(Calendar.MINUTE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_reset:
                Intent intent = new Intent(AddEventTimeActivity.this, EventSelectorActivity.class);
                intent.putExtra("come_from", "add_event_time");
                startActivity(intent);
                finish();
                break;
            case R.id.btn_set_start_date:
                DatePickerDialog datePickerDialog = new DatePickerDialog(AddEventTimeActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {
                        startDate.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " ");
                        time.setYear(year);
                        time.setMonth(monthOfYear);
                        time.setDay(dayOfMonth);
                    }
                }, year, monthOfYear, dayOfMonth);
                datePickerDialog.show();
                break;
            case R.id.btn_set_start_time:
                TimePickerDialog timePickerDialog = new TimePickerDialog(AddEventTimeActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        startTime.setText(hourOfDay + ":" + minute + ":" + "00");
                        time.setHour(hourOfDay);
                        time.setMinute(minute);
                    }
                }, hourOfDay, minute, true);
                timePickerDialog.show();
                break;
            case R.id.btn_save:
                if (!TextUtils.isEmpty(hour.getText()) && !TextUtils.isEmpty(min.getText())) {
                    getHour = Integer.valueOf(hour.getText().toString());
                    getMin = Integer.valueOf(min.getText().toString());
                    if (!TextUtils.isEmpty(startDate.getText()) && !TextUtils.isEmpty(startTime.getText())) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(time.getYear(), time.getMonth(), time.getDay(), time.getHour(), time.getMinute());
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        startDateTime.delete(0, startDateTime.length());
                        startDateTime.append(format.format(calendar.getTime()));
                        if (startDateTime.toString().compareTo(format.format(Calendar.getInstance().getTime()).toString()) < 0) {
                            showSaveDialog();
                        } else{
                            Toast.makeText(AddEventTimeActivity.this, "活动开始时间不能超过现在时间", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(AddEventTimeActivity.this, "请选择活动开始日期", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(AddEventTimeActivity.this, "请输入活动用时", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
    private void showSaveDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(AddEventTimeActivity.this);
        builder.setTitle("保存");
        builder.setMessage("保存：" + getIntent().getStringExtra("event_name") + "活动\n活动用时：" + getHour + "时" +
                "" + getMin + "分\n开始时间" + startDateTime.toString());
        builder.setCancelable(false);
        builder.setPositiveButton("确定保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EventTime eventTime = new EventTime();
                eventTime.setEventId(getIntent().getIntExtra("event_id", 0));
                eventTime.setElapsedTime((getHour * 60 + getMin) * 60 * 1000);
                eventTime.setStartDateTime(startDateTime.toString());
                if (timeManagerDB.saveEventTime(eventTime) > 0) {
                    Toast.makeText(MyApplication.getContext(), "保存成功！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(AddEventTimeActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }
        });
        builder.setNegativeButton("返回修改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }
}
